<template>
  <div class="auth-container">
    <el-card class="auth-card tags-card">
      <template #header>
        <div class="card-header">
          <h2>标签管理</h2>
          <p class="subtitle">为你的日志添加清晰的分类</p>
        </div>
      </template>

      <div class="toolbar">
        <el-input v-model="newTag" placeholder="新标签名称" size="large" class="toolbar-item" />
        <el-button type="primary" size="large" :loading="loading" :disabled="!newTag.trim()" @click="addTag">添加</el-button>
      </div>

      <el-table :data="tags" border :loading="loading">
        <el-table-column prop="name" label="名称" />
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button link type="primary" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useTagsStore } from '@/stores/tags'
import { storeToRefs } from 'pinia'

const tagsStore = useTagsStore()
const { list: tags, loading } = storeToRefs(tagsStore)
const newTag = ref('')

onMounted(async () => {
  try {
    // console.log('Mounted TagsView.vue')
    await tagsStore.fetch()
  } catch (e: any) {
    ElMessage.error(e?.message || '加载标签失败')
  }
})

async function addTag() {
  const name = newTag.value.trim()
  if (!name) return
  try {
    const created = await tagsStore.add(name)
    newTag.value = ''
    ElMessage.success('已添加标签')
    await tagsStore.fetch()
  } catch (e: any) {
    ElMessage.error(e?.message || '添加标签失败')
  }
}

async function remove(id: number) {
  try {
    await tagsStore.remove(id)
    ElMessage.success('已删除')
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}
</script>

<style scoped>
.tags-card { max-width: 900px; margin: 40px auto; }
.subtitle { margin: 6px 0 0; font-size: 14px; color: #8a6f5b; }
.toolbar { display: flex; gap: 12px; margin-bottom: 12px; }
.toolbar-item { min-width: 220px; }
</style>